package io.zjw.testblelib.util;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.time.LocalDateTime;
import cn.jesse.nativelogger.NLogger;
import io.zjw.testblelib.MyClient;

public class SendData {
    private static String TAG = "SendData";
//    private static MyClient myClient = null;
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static  void sendData(Object values,String serverIP, String flag,MyClient myClient) {
        JSONObject dataJson = new  JSONObject();
        String url = "ws://"+ serverIP+":54378/ws";
//        try {
////            myClient = new  MyClient(url);
//            myClient.connectBlocking();
//        } catch (Exception e) {
//            e.printStackTrace();
//            NLogger.e(TAG,e.getMessage());
//        }
        if (myClient.isOpen()){
            try {
                dataJson.put("flag",flag);
                dataJson.put("data",values);
                dataJson.put("date", LocalDateTime.now().toString());
                myClient.send(dataJson.toString());
            }catch (Exception e){
                myClient.send(dataJson.toString());
                Log.i(TAG,flag+"-----"+dataJson);
            }
        }else{
            String status = myClient.getReadyState().toString();
//            Log.d(TAG, "myClient: 通道异常"+ myClient.getReadyState().toString() );
            if (status.equals("CLOSING") || status.equals("CLOSED")) {
                myClient.reconnect();
            }
            if(myClient.isOpen()){
                myClient.send(dataJson.toString());
            }
        }
    }
}
